<template>
  <div v-loading="loading" class="manage-coupon">
    <el-collapse-transition>
      <div v-show="!isShowDetail">
        <div class="top">
          <el-row v-if="couponList.length > 0" :gutter="30">
            <el-col
              v-for="item in couponList"
              :key="item.type"
              :xs="12"
              :sm="8"
              :md="8"
              :lg="8"
              :xl="6"
            >
              <el-card
                :body-style="{ padding: 0 }"
                class="box-card"
                shadow="hover"
              >
                <div class="card-info">
                  <div class="info-top">
                    <div class="type app-line-one">{{ item.name }}</div>
                    <el-button
                      size="small"
                      type="primary"
                      @click.native="jumpAdd(item)"
                      >创建</el-button
                    >
                  </div>
                  <div class="describe app-line-two">
                    {{ item.description }}
                  </div>
                </div>
                <div class="btn-group" />
              </el-card>
            </el-col>
          </el-row>
          <div class="tab">
            <el-tabs v-model="filterForm.status" @tab-click="changeTab">
              <el-tab-pane label="运营中" name="2" />
              <!-- <el-tab-pane label="报名中" name="6" /> -->
              <el-tab-pane label="草稿箱" name="1" />
              <el-tab-pane label="已暂停" name="3" />
              <el-tab-pane label="已终止" name="4" />
              <el-tab-pane label="已过期" name="5" />
            </el-tabs>
          </div>
        </div>

        <!-- 列表 -->
        <div class="content-main app-main-content-box">
          <!--筛选-->
          <el-form
            ref="filterForm"
            :inline="true"
            :model="filterForm"
            label-width="70px"
            size="small"
          >
            <el-form-item label="名称：" prop="couponName"
              ><el-input
                v-model="filterForm.couponName"
                placeholder="请输入"
                clearable
            /></el-form-item>
            <el-form-item label="批次：" prop="stockId"
              ><el-input
                v-model="filterForm.stockId"
                placeholder="请输入"
                clearable
                maxlength="9"
                oninput="value=value.replace(/^\.+|[^\d.]/g,'')" 
            /></el-form-item>
            <el-form-item label="类型：" prop="types">
              <el-select
                v-model="filterForm.types"
                filterable
                multiple
                collapse-tags
                placeholder="请选择"
                class="w-400"
                @change="(val) => idsChange(val, 'couponType')"
              >
                <el-option label="所有类型" value />
                <el-option
                  v-for="(v, k) in couponTypeOptions"
                  :key="k"
                  :label="v"
                  :value="k"
                />
              </el-select>
            </el-form-item>
            <el-form-item label-width="0">
              <el-button type="primary" round @click="submitFilterForm"
                >查 询</el-button
              >
              <el-button round @click="resetFilterForm">重 置</el-button>
            </el-form-item>
          </el-form>

          <div>
            <el-row v-if="list.length > 0" :gutter="30" type="flex">
              <el-col
                v-for="(v, i) in list"
                :key="i"
                :xs="12"
                :sm="8"
                :md="8"
                :lg="8"
                :xl="6"
                class="coupon-card"
              >
                <div v-if="v.couponTag == 1" class="coupon-labelType">
                  商圈券
                </div>
                <el-card shadow="hover" @click.native="showDetail(v)">
                  <div class="coupon-content">
                    <div class="coupon-base">
                      <div class="left">
                        <img v-if="v.icon" :src="fileBaseUrl + v.icon" alt />
                        <el-image
                          v-else
                          :src="
                            'static/icon/coupon/i-coupon-' +
                            v.couponType +
                            '.png'
                          "
                          fit="fill"
                        />
                      </div>
                      <div class="right">
                        <div class="name app-line-one">{{ v.couponName }}</div>
                        <div class="type app-line-one">
                          批次号：{{ v.id }} |
                          {{ couponTypeOptions[v.couponType] }}
                        </div>
                      </div>
                    </div>
                    <div class="coupon-detail">
                      <div
                        v-if="couponTypeGroup.cash.includes(v.couponType)"
                        class="cash"
                      >
                        {{ v.denomination / 100 }}元
                      </div>
                      <div
                        v-if="couponTypeGroup.discount.includes(v.couponType)"
                        class="discount"
                      >
                        {{ v.discountPercent / 10 }}折
                      </div>
                      <div
                        v-if="couponTypeGroup.exchange.includes(v.couponType)"
                        class="exchange"
                      >
                        {{ v.exchangeThings }}
                      </div>
                      <div
                        v-if="couponTypeGroup.cash.includes(v.couponType)"
                        class="describe"
                      >
                        订单满{{ v.transactionMinimum / 100 }}元可用{{
                          v.maxUseNum && v.maxUseNum > 1
                            ? "，最多叠加" + v.maxUseNum + "张"
                            : ""
                        }}
                      </div>
                    </div>
                    <div class="coupon-more">
                      <div class="date">
                        有效期：{{ v.startTime + " ~ " + v.endTime }}
                      </div>
                      <div class="belong">
                        归属人：{{
                          `${v.belongMerchantName}（${v.belongMerchant}）`
                        }}
                      </div>
                    </div>
                    <div v-if="v.status === 1" class="coupon-status">
                      <div
                        v-if="
                          !v.channelSync &&
                          ['cash_wx_busi', 'discount_wx_busi'].includes(
                            v.couponType
                          ) &&
                          v.syncMsg
                        "
                        class="app-text-color-danger"
                      >
                        券渠道同步失败，请检查
                        <el-tooltip
                          popper-class="el-tooltip-theme-fresh"
                          placement="top"
                          effect="light"
                        >
                          <div slot="content">{{ v.syncMsg }}</div>
                          <i class="el-icon-warning" />
                        </el-tooltip>
                      </div>
                      <div
                        v-else-if="
                          !v.channelSync &&
                          ['cash_wx_busi', 'discount_wx_busi'].includes(
                            v.couponType
                          )
                        "
                        class="app-text-color-warning"
                      >
                        该批次需同步券渠道
                      </div>
                      <div v-else class="app-text-color-primary">
                        该批次激活即可使用
                      </div>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
            <div v-else class="empty-text">暂无数据</div>
          </div>
        </div>
      </div>
    </el-collapse-transition>

    <!-- 效果详情 -->
    <el-collapse-transition
      ><CouponInfo v-if="isShowDetail" ref="couponInfo"
    /></el-collapse-transition>

    <DialogSyncWxPayCoupon ref="dialogSyncWxPayCoupon" />
  </div>
</template>

<script>
import DialogSyncWxPayCoupon from "./components/DialogSyncWxPayCoupon";
import CouponInfo from "./components/CouponInfo";
import { couponList } from "../../api/coupon";
import { mapActions, mapGetters } from "vuex";

export default {
  components: {
    CouponInfo,
    DialogSyncWxPayCoupon,
  },
  data() {
    return {
      // 配置
      couponTypeOptions: {
        cash: "代金券",
        cash_wx_pay: "微信支付代金券",
        cash_wx_busi: "微信商家代金券",
        discount: "折扣券",
        discount_wx_busi: "微信商家折扣券",
        exchange: "兑换券",
      },
      couponTypeGroup: {
        cash: ["cash", "cash_wx_pay", "cash_wx_busi"],
        discount: ["discount", "discount_wx_busi"],
        exchange: ["exchange"],
      },
      // 状态
      loading: false,
      isShowDetail: false,
      // 数据
      list: [], // 列表
      lastCouponTypesIds: [],
      couponTypesIds: [
        "",
        "cash",
        "cash_wx_pay",
        "cash_wx_busi",
        "discount",
        "discount_wx_busi",
        "exchange",
      ],
      filterForm: {
        status: "2",
        couponName: null,
        stockId: null,
        types: [],
      },
      couponList: [
        {
          source: "coupon",
          type: "cash",
          name: "满减券",
          description: "使用时抵扣部分金额，支持多张叠加使用",
          icon: "i-coupon-cash",
        },
        {
          source: "coupon",
          type: "discount",
          name: "折扣券",
          description: "使用时按折扣计算抵扣金额，支持最大抵扣上限",
          icon: "i-coupon-discount",
        },
        // {
        //   source: "coupon",
        //   type: "exchange",
        //   name: "兑换券",
        //   description: "只支持核销，用于一些兑换场景，不支持线上订单核销",
        //   icon: "i-coupon-exchange",
        // },
      ],
    };
  },
  computed: {
    ...mapGetters(["fileBaseUrl"]),
  },
  activated() {
    this.isShowDetail = false;
    this.fetchData();
    this.getActiveMaIsOnline();
  },
  created() {},
  mounted() {
    // this.fetchData()
    // this.getActiveMaIsOnline()
  },
  methods: {
    /**
     *  获取数据
     */
    // 获取小程序是否上线
    ...mapActions(["getAuthMa"]),
    getActiveMaIsOnline() {
      this.getAuthMa();
    },

    // 列表
    fetchData() {
      this.loading = true;
      const params = this.filterForm;
      couponList(params)
        .then((res) => {
          this.list = res.data;
        })
        .catch((err) => {})
        .finally(() => {
          this.loading = false;
        });
    },

    /**
     * 按钮组
     */
    // 切换tab
    changeTab(e) {
      if (e.name == 6) {
        this.filterForm.status = "6";
      }
      this.fetchData();
    },

    // 查询
    submitFilterForm() {
      this.fetchData(1);
    },

    // 重置
    resetFilterForm() {
      this.$refs.filterForm.resetFields();
      this.fetchData(1);
    },

    // 获取详情
    showDetail(row) {
      this.isShowDetail = true;
      this.$nextTick(() => {
        this.$refs.couponInfo.open(row).then((res) => {
          this.fetchData();
          this.isShowDetail = false;
        });
      });
    },

    openSyncWxPayCoupon() {
      this.$refs.dialogSyncWxPayCoupon.open().then(() => {});
    },

    //

    /**
     * 状态组
     */
    // 多选改变
    idsChange(val, type) {
      let lastIdsType = "";
      let idsType = "";
      let allIds = "";
      switch (type) {
        case "couponType":
          lastIdsType = "lastCouponTypesIds";
          idsType = "types";
          allIds = "couponTypesIds";
          break;
      }
      const lastVal = this[lastIdsType];
      if (val.includes("")) {
        this.filterForm[idsType] = this[allIds];
      }
      if (lastVal.includes("") && !val.includes("")) {
        this.filterForm[idsType] = [];
      }
      if (lastVal.includes("") && val.includes("")) {
        val.splice(
          val.findIndex((v) => v === ""),
          1
        );
        this.filterForm[idsType] = val;
      }
      if (!lastVal.includes("") && !val.includes("")) {
        if (val.length === this[allIds].length - 1) {
          this.filterForm[idsType] = [""].concat(val);
        }
      }
      this[lastIdsType] = this.filterForm[idsType];
    },
    jumpAdd(item) {
      // 判断是否是服务商模式
      // 跳转券
      if (item.source === "coupon") {
        this.$router.push({
          name: "PublicCardsAndOfferEditCoupon",
          query: { mode: "add", couponType: item.type },
        });
      } else if (item.source === "card") {
        this.$router.push({
          name: "PublicCardsAndOfferEditCard",
          query: { mode: "add", cardType: item.type },
        });
      }
    },
  },
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/* tab */
::v-deep {
  .el-tabs__header {
    margin-bottom: 0;
    background-color: #fff;
    border-radius: 0 0 5px 5px;
  }

  .el-tabs__nav-wrap::after {
    background-color: #fff;
  }

  .el-tabs__active-bar {
    height: 4px;
  }

  .el-row {
    flex-wrap: wrap;
  }

  .el-card,
  .el-card__body {
    height: 100%;
  }
}

/* 头部 */
.top {
  padding: 24px 30px 0;
  border-radius: 5px 5px;
  background-color: #fff;
  margin-bottom: 10px;

  .title {
    font-size: 20px;
  }
  .card-info {
    padding: 15px;
    .info-top {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .type {
      font-size: 20px;
      font-weight: bold;
    }
    .describe {
      margin-top: 10px;
      font-size: 14px;
      color: $light-font-color;
    }
    // }
  }
}

.empty-text {
  line-height: 60px;
  text-align: center;
  color: #909399;
  font-size: 14px;
}

/* 卡片 */
.coupon-card {
  margin-bottom: 20px;
  //height: 270px;
  cursor: pointer;
  position: relative;
  .coupon-labelType {
    position: absolute;
    top: 0;
    right: 15px;
    background-color: $primary;
    color: white;
    padding: 5px 10px;
  }

  .coupon-content {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 100%;
  }

  .coupon-base {
    display: flex;

    .left {
      overflow: hidden;
      flex: 0 0 auto;
      width: 80px;
      height: 80px;
      margin-right: 15px;
      border-radius: 50%;
      border: 1px solid #e7e7e7;
    }

    .right {
      flex: 1 1 auto;
      display: flex;
      flex-direction: column;
      justify-content: center;

      .name {
        font-size: 20px;
        // margin-top: 25px;
        font-weight: bold;
      }

      .type {
        margin-top: 5px;
        font-size: 14px;
        color: #909399;
      }
    }
  }

  .coupon-detail {
    text-align: center;
    border-bottom: 1px solid #e7e7e7;
    height: 90px;

    .cash,
    .discount,
    .exchange {
      font-size: 24px;
      margin-top: 10px;
      font-weight: bold;
    }

    .describe {
      margin-top: 10px;
      font-size: 14px;
      color: #909399;
    }
  }

  .coupon-more {
    margin-top: 10px;
    font-size: 14px;
    color: #909399;

    .date {
    }

    .belong {
    }
  }

  .coupon-status {
    margin-top: 10px;
    padding-top: 10px;
    border-top: 1px solid #e7e7e7;
    font-size: 14px;
  }
}
</style>
